package com.qunar.wan.support.lucene;

import com.qunar.wan.common_api.service.ConvertService;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;

import java.io.IOException;
import java.util.List;

/**
 * Created by hiCyoung on 13-12-1.
 */
public class DocumentWriter {
    private DocumentWriter() {
    }

    public static <T, K> void addIndexDoc(ConvertService<T, K> convertService, T t) throws IOException {
        IndexWriter indexWriter = LuceneContext.getIndexWriter();
        Document doc = convertService.convert2Doc(t);
        if (indexWriter.getConfig().getOpenMode() == IndexWriterConfig.OpenMode.CREATE) {
            indexWriter.addDocument(doc);
        } else {
            indexWriter.updateDocument(convertService.updateIndexTerm(t), doc);
        }
        LuceneContext.commitChangesVisible();
    }

    public static void addIndexDocs(ConvertService convertService, List objs) throws IOException {
        IndexWriter indexWriter = LuceneContext.getIndexWriter();
        for (Object obj : objs) {
            Document doc = convertService.convert2Doc(obj);
            if (indexWriter.getConfig().getOpenMode() == IndexWriterConfig.OpenMode.CREATE) {
                indexWriter.addDocument(doc);
            } else {
                indexWriter.updateDocument(convertService.updateIndexTerm(obj), doc);
            }
        }
        LuceneContext.commitChangesVisible();
    }

}
